// pages/sureorder/sureorder.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    markers: [{
      iconPath: "/pages/images/address.png",
      id: 0,
      latitude: 23.099994,
      longitude: 113.324520,
      width: 50,
      height: 50
    }],
    active: 1,
    showcoupon: 0,
    canusecoupon: [],
    CartIDStr: "",
    sureorderlist: "",
    allmoney: 0,
    shownum: 3,
    yixuancoupon: "",
    xiaoji: 0,
    bz: "",
    ordermsg: "",
    ischeck: false,
    youhuiid: [],
    currentaddress: "",
    canusenum: 0,
    allcouponmoney: 0,
    chaduoshao:"",

    JSCouponID: "",
    WholeCouponID: "",


    showjuli: false,
    canclick: true,

    nammee: "",
    chaoshi: ""
  },


  rad: function(d) {
    return d * Math.PI / 180.0;
  },


  // 根据经纬度计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
  getDistance: function(lat1, lng1, lat2, lng2) {

    var radLat1 = this.rad(lat1);
    var radLat2 = this.rad(lat2);
    var a = radLat1 - radLat2;
    var b = this.rad(lng1) - this.rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    //输出为公里

    var distance = s;
    var distance_str = "";

    if (parseInt(distance) >= 1) {
      distance_str = distance.toFixed(1) + "km";
    } else {
      distance_str = distance * 1000 + "m";
    }

    //s=s.toFixed(4);

    // console.info('lyj 距离是', s);
    // console.info('lyj 距离是', distance_str);
    return s;
  },


  canpeisong: function() {
    var lat1 = this.data.currentaddress.latitude
    var lng1 = this.data.currentaddress.Longitude

    var lat2 = this.data.sureorderlist[0].lat
    var lng2 = this.data.sureorderlist[0].lng

    var juli = this.getDistance(lat1, lng1, lat2, lng2)
    console.log(juli, "距离啊")

    if (juli > this.data.sureorderlist[0].PSDistance) {
      this.setData({
        showjuli: true
      })
      return 0
    } else {
      return 1
    }

  },

  tcshowjuli: function() {

    this.setData({
      showjuli: false,
      canclick: true
    })
  },


  getlistalladdress: function(Defaultaddress, siteid) {
    ajax('/api/Myaddress/Get?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      Defaultaddress: Defaultaddress
    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "get",
    }, res => {
      console.log(res)
      console.log(siteid)
      if (res.Models != null) {
        if (siteid != "") {
          for (var x in res.Models) {
            if (res.Models[x].ID == siteid) {
              this.setData({
                currentaddress: res.Models[x]
              })
            }
          }
        } else {
          this.setData({
            currentaddress: res.Models[0]
          })
        }


      } else {
        this.setData({
          currentaddress: null
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var CartIDStr = options.CartIDStr
    this.setData({
      CartIDStr: CartIDStr
    })
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000',
    })

    this.getsureorderlist()


  },

  lookgengduo: function() {
    if (this.data.shownum == 3) {
      this.setData({
        shownum: 100
      })
    } else {
      this.setData({
        shownum: 3
      })
    }

  },

  toselectaddress: function() {
    this.setData({
      showjuli: false
    })
    wx.navigateTo({
      url: '/pages/selectaddress/selectaddress',
    })
  },



  getsureorderlist: function() {
    ajax('/api/ShoppingCartgo/Aftersale?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      strID: this.data.CartIDStr,

    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "get",
    }, res => {
      console.log(res)

      // console.log("11111111111111111111111111111")
      this.setData({
        sureorderlist: res.Models
      })
      var chaoshi = []
      // chaoshi: [{
      //   iconPath: "/resources/others.png",
      //   id: 0,
      //   latitude: 23.099994,
      //   longitude: 113.324520,
      //   width: 50,
      //   height: 50
      // }],

      var objj = {}
      objj.iconPath = "/pages/images/tuijian.png"
      objj.id = 0
      objj.latitude = res.Models[0].lat
      objj.longitude = res.Models[0].lng
      objj.width = 20
      objj.height = 20
      objj.name = res.Models[0].ShopName

    
      chaoshi.push(objj)

      this.setData({
        chaoshi: chaoshi
      })


      if (this.data.sureorderlist[0].data.length == 1) {
        this.setData({
          JSCouponID: ''
        })
      } else if (this.data.sureorderlist[0].data.length > 1) {
        this.setData({
          JSCouponID: []
        })
      }

      var allmoney = 0
      for (var x in res.Models[0].data) {
        allmoney = allmoney + res.Models[0].data[x].Productmoney
      }
      this.setData({
        allmoney: allmoney.toFixed(2)
      })
      this.xiaoji()


      this.getcoupon()
    })
  },

  select: function(e) {
    var index = e.currentTarget.dataset.index
    if (index == 2) {
      if (this.data.sureorderlist[0].ah == 0) {
        wx.showToast({
          title: '未开启送货上门',
          icon: 'none',
          duration: 2000
        })
        this.setData({
          active: 1
        })
      } else {
        this.setData({
          active: index
        })
        this.xiaoji()

        if (this.data.siteid) {
          this.getlistalladdress(1, this.data.siteid)
        } else {
          this.getlistalladdress(0, "")
        }
      }

    } else {
      this.setData({
        active: index
      })
      this.xiaoji()
    }
  },
  tctc: function() {
    var nammee = ""
    var name = ''

    if (this.data.WholeCouponID != '') {
      for (var x in this.data.canusecoupon[0]) {
        if (this.data.canusecoupon[0][x].ReceiveCouponID == this.data.WholeCouponID) {
          name = this.data.canusecoupon[0][x].CouponName + ","
        }
      }
    }

    var name2 = ''

    if (this.data.JSCouponID != '') {
      if ((typeof this.data.JSCouponID == 'object') && this.data.JSCouponID.constructor == Array) {
        for (var x in this.data.canusecoupon[2]) {

          for (var y in this.data.JSCouponID) {

            if (this.data.canusecoupon[2][x].ReceiveCouponID == this.data.JSCouponID[y]) {

              name2 += this.data.canusecoupon[2][x].CouponName + ","
            }
          }

        }
      } else {
        for (var x in this.data.canusecoupon[1]) {

          if (this.data.canusecoupon[1][x].ReceiveCouponID == this.data.JSCouponID) {
            // console.log()
            name2 = this.data.canusecoupon[1][x].CouponName
          }
        }
        for (var x in this.data.canusecoupon[2]) {

          if (this.data.canusecoupon[2][x].ReceiveCouponID == this.data.JSCouponID) {
            // console.log()
            name2 = this.data.canusecoupon[2][x].CouponName
          }
        }
      }
    }
    nammee = name + name2
    this.setData({
      nammee: nammee
    })




    this.allcouponmoney()
    this.setData({
      showcoupon: 0
    })
  },


  remove: function(array, val) {
    var index = array.indexOf(val);
    if (index > -1) {
      array.splice(index, 1);
    }
  },

  allcouponmoney: function() {
    var JSCouponID = this.data.JSCouponID
    var WholeCouponID = this.data.WholeCouponID

    var allcouponmoney = 0
    var array = []

    if ((typeof JSCouponID == 'object') && JSCouponID.constructor == Array) {
      for (var x in JSCouponID) {
        array.push(JSCouponID[x])
      }
    } else {
      array.push(JSCouponID)
    }
    array.push(WholeCouponID)
    console.log(array)

    for (var x in this.data.canusecoupon) {
      for (var y in this.data.canusecoupon[x]) {
        if (array.indexOf(this.data.canusecoupon[x][y].ReceiveCouponID) != -1) {
          allcouponmoney += this.data.canusecoupon[x][y].CouponMoney
        }
      }
    }
    this.setData({
      allcouponmoney: allcouponmoney
    })
    this.xiaoji()
  },

  clickdanxuans: function(e) {

    var index = e.currentTarget.dataset.index
    var fuindex = e.currentTarget.dataset.fuindex
    console.log(index)
    console.log(fuindex)

    var array = this.data.canusecoupon;

    var weizhi = "canusecoupon[" + fuindex + "][" + index + "]." //这里需要将设置的属性用字符串进行拼接

    // 取消选择
    if (array[fuindex][index].ischeck) {
      if (fuindex == 0) {
        //无
        for (var x in array[fuindex]) {
          var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
          this.setData({
            [weizhi1 + "cantuse"]: false,
          })
        }
        this.setData({
          [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
          WholeCouponID: ""
        })
      } else if (fuindex == 1) {
        //全
        for (var x in array[fuindex]) {
          var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
          this.setData({
            [weizhi1 + "cantuse"]: false,
          })
        }
        for (var x in array[2]) {
          var weizhi1 = "canusecoupon[" + 2 + "][" + x + "]."
          this.setData({
            [weizhi1 + "cantuse"]: false,
          })
        }
        this.setData({
          [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
          JSCouponID: ""
        })

        if (this.data.sureorderlist[0].data.length == 1) {
          this.setData({
            JSCouponID: ''
          })
        } else if (this.data.sureorderlist[0].data.length > 1) {
          this.setData({
            JSCouponID: []
          })
        }
      } else if (fuindex == 2) {
        // 单个商品
        if (this.data.sureorderlist[0].data.length == 1) {
          for (var x in array[fuindex]) {
            var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
            this.setData({
              [weizhi1 + "cantuse"]: false,
            })
          }

          for (var x in array[1]) {
            var weizhi1 = "canusecoupon[" + 1 + "][" + x + "]."
            this.setData({
              [weizhi1 + "cantuse"]: false,
            })
          }

          this.setData({
            [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
            JSCouponID: ""
          })
        }
        //多个
        else {
          var JSCouponID = this.data.JSCouponID
          if (JSCouponID.length == 1) {
            for (var x in array[1]) {
              var weizhi1 = "canusecoupon[" + 1 + "][" + x + "]."
              this.setData({
                [weizhi1 + "cantuse"]: false,
              })
            }
          }

          var ActivityID = array[fuindex][index].ActivityID
          for (var x in array[fuindex]) {

            if (x == index) {
              var JSCouponID = this.data.JSCouponID
              // console.log(JSCouponID)
              // console.log("aaaaaaaa")

              JSCouponID.pop(JSCouponID.indexOf(array[fuindex][index].ReceiveCouponID))

              this.setData({
                [weizhi + "cantuse"]: false,
                [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
                JSCouponID: JSCouponID
              })
            } else {
              console.log(array[fuindex][x].ActivityID)
              if (ActivityID == array[fuindex][x].ActivityID) {
                var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
                this.setData({
                  [weizhi1 + "cantuse"]: false,
                })
              }
            }
          }

        }
      }
    }
    // 选择
    else if (!array[fuindex][index].ischeck) {
      if (fuindex == 0) {
        //无
        console.log("cantuse")

        for (var x in array[fuindex]) {
          if (x == index) {
            this.setData({
              [weizhi + "cantuse"]: false,
              [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
              WholeCouponID: array[fuindex][index].ReceiveCouponID
            })
          } else {
            var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
            this.setData({
              [weizhi1 + "cantuse"]: true,
            })
          }
        }
      } else if (fuindex == 1) {
        //全

        for (var x in array[fuindex]) {
          if (x == index) {
            this.setData({
              [weizhi + "cantuse"]: false,
              [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
              JSCouponID: array[fuindex][index].ReceiveCouponID
            })
          } else {
            var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
            this.setData({
              [weizhi1 + "cantuse"]: true,
            })
          }
        }

        for (var x in array[2]) {
          var weizhi1 = "canusecoupon[" + 2 + "][" + x + "]."
          this.setData({
            [weizhi1 + "cantuse"]: true,
          })
        }

      } else if (fuindex == 2) {
        // 单个商品
        if (this.data.sureorderlist[0].data.length == 1) {
          for (var x in array[fuindex]) {
            if (x == index) {
              this.setData({
                [weizhi + "cantuse"]: false,
                [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
                JSCouponID: array[fuindex][index].ReceiveCouponID
              })
            } else {
              var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
              this.setData({
                [weizhi1 + "cantuse"]: true,
              })
            }
          }
          for (var x in array[1]) {
            var weizhi1 = "canusecoupon[" + 1 + "][" + x + "]."
            this.setData({
              [weizhi1 + "cantuse"]: true,
            })
          }
        }
        //多个商品 
        else {
          for (var x in array[1]) {
            var weizhi1 = "canusecoupon[" + 1 + "][" + x + "]."
            this.setData({
              [weizhi1 + "cantuse"]: true,
            })
          }
          var ActivityID = array[fuindex][index].ActivityID
          for (var x in array[fuindex]) {

            if (x == index) {
              var JSCouponID = this.data.JSCouponID
              console.log(JSCouponID)
              console.log("aaaaaaaa")

              JSCouponID.push(array[fuindex][index].ReceiveCouponID)

              this.setData({
                [weizhi + "cantuse"]: false,
                [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
                JSCouponID: JSCouponID
              })
            } else {
              console.log(array[fuindex][x].ActivityID)
              if (ActivityID == array[fuindex][x].ActivityID) {
                var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
                this.setData({
                  [weizhi1 + "cantuse"]: true,
                })
              }
            }
          }

        }
      }
    }
  },

  queren: function() {
    this.allcouponmoney()
    this.setData({
      showcoupon: 0
    })

  },
  tccoupon: function() {
    this.setData({
      showcoupon: 1
    })
  },


  getcoupon: function() {
    var ActivityIDStrlist = []
    for (var x in this.data.sureorderlist[0].data) {
      ActivityIDStrlist.push(this.data.sureorderlist[0].data[x].ID)
    }


    ajax('/api/CouponCollection/Get?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),


      ActivityIDStr: ActivityIDStrlist.join(","),
      Vtype: 2,
      // PTID: this.data.CartIDStr, 

      PageIndex: 0,
      ProvinceName: wx.getStorageSync('address_component').province,
      CityName: wx.getStorageSync('address_component').city,
      DistrictName: wx.getStorageSync('address_component').district,
      Title: "",
    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "get",
    }, res => {
      console.log(res)

      var wu = []
      var quan = []
      var zhiding = []

      for (var a in res.Models) {
        res.Models[a].ischeck = false
        res.Models[a].cantuse = false
        if (res.Models[a].ZDMoney <= this.data.allmoney) {
          res.Models[a].cantman = false
          var canusenum = this.data.canusenum += 1
          this.setData({
            canusenum: canusenum
          })
        } else {
          res.Models[a].cantman = true
        }

        if (res.Models[a].CouponType == 0) {
          wu.push(res.Models[a])

        }
        if (res.Models[a].CouponType == 2) {
          quan.push(res.Models[a])
        }
        if (res.Models[a].CouponType == 3) {
          zhiding.push(res.Models[a])
        }
      }

      var list = []
      list.push(wu)
      list.push(quan)
      list.push(zhiding)
      // 优惠券类型
      // 0 无门槛(跳转首页)
      // 1指定活动满减(跳转拼购详情)
      // 2全品满减劵(跳转商户)
      // 3指定商品满减劵(跳转商户商品详情)
      // 4活动免费领(暂时无效)
      // 5商品免费领(暂时无效)

      this.setData({
        canusecoupon: list
      })


    })
  },
  topay: function() {
    wx.navigateTo({
      url: '/pages/pay/pay',
    })
  },

  xiaoji: function() {
    var allmoney = Number(this.data.allmoney)
    console.log(allmoney)
    console.log("1111111111")

    // 加运费
    if (this.data.active == 2) {

      if (allmoney >= this.data.sureorderlist[0]. QSMoney){
       // 判断是否免运费
       if (allmoney < this.data.sureorderlist[0].MPSMoney) {

         allmoney += this.data.sureorderlist[0].PSMoney

       } else {
         console.log(allmoney)
         // allmoney -= this.data.sureorderlist[0].PSMoney
       }
     }else{
       var chaduoshao = (this.data.sureorderlist[0].QSMoney - this.data.allmoney).toFixed(2)
       this.setData({
         chaduoshao: chaduoshao
       })
     }

      

      console.log(allmoney)
      console.log("1111111111")
    }

    // 减掉已优惠
    allmoney -= this.data.allcouponmoney



    this.setData({
      xiaoji: allmoney.toFixed(2)
    })

  },

  getinputbz: function(e) {
    var bz = e.detail.value
    this.setData({
      bz: bz
    })
  },
  btntijiao: function() {
    if (this.data.canclick == false) {
      return
    }

    this.setData({
      canclick: false
    })


    if (this.data.active==2){
      if (this.data.currentaddress == null) {
        wx.showToast({
          title: "请选择收货地址",
          icon: 'none',
          duration: 1000
        })
        return
      }
      var aa = this.canpeisong()
      if (aa == 0) {
        return
      }
    }

    

    console.log("dddddddd")
    // {
    //   "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzaWduSWQiOjM4NjYsImRlYWxlcmlkIjozMDkxLCJ1c2VyaWQiOjMyMzEsImRlYWlkIjozMjMxLCJ1c2VydHlwZSI6MywicG5hbWUiOiIxMzY5MTUyMzU1OSIsInRpbWVzIjoxNTY5MDI4OTk1LCJVc2VyTmFtZSI6IjEzNjkxNTIzNTU5IiwiTW9iaWxlUGhvbmUiOiIxMzY5MTUyMzU1OSIsIkNpdHkiOjExMDEwMCwiUHJvdmluY2UiOjExMDAwMCwiRGlzdHJpY3QiOjExMDExNn0.LiLUhCjv-lCpX7890oD7536qtci6q48yZm54-dVySJ0",
    //   "query": [{
    //     "ShopID": 18,
    //     "SHWay": 1,
    //     "Orderaddress": "怀柔区政府",
    //     "freight": 0,
    //     "ReceiveCouponID": "1,2,3",
    //     "Longitude": "116.31097147915256",
    //     "latitude": "40.05257767513591",
    //     "InvoiceID": -1,
    //     "IMoney": 35,
    //     "PersonAddress": 122,
    //     "Remark": "",
    //     "Orders": [{
    //       "PGID": 329,
    //       "SKUID": 668,
    //       "OrderNumber": 1,
    //       "CartID": 1723
    //     }]
    //   }]
    // }
    var query = []
    // for (var x in sureorderlist){

    // }
    var obj = {}
    var Orders = []
    var info = this.data.sureorderlist[0]
    obj.ShopID = info.key
    // ：1：自提2：送货上门
    obj.SHWay = this.data.active

    if (this.data.active == 1) {
      obj.Orderaddress = info.Address
      obj.Longitude = info.lng
      obj.latitude = info.lat
    } else if (this.data.active == 2) {
      obj.Orderaddress = this.data.currentaddress.Locationaddress
      obj.Longitude = this.data.currentaddress.Longitude
      obj.latitude = this.data.currentaddress.latitude
      obj.PersonAddress = this.data.currentaddress.ID
    }

    if (this.data.active == 2 ){
      if (this.data.allmoney >= this.data.sureorderlist[0].MPSMoney) {
        obj.freight = 0
      } else {
        obj.freight = this.data.sureorderlist[0].PSMoney
      }
    }else{
      obj.freight = 0
    }
    

    var JSCouponID = this.data.JSCouponID
    var WholeCouponID = this.data.WholeCouponID


    if ((typeof JSCouponID == 'object') && JSCouponID.constructor == Array) {
      if (JSCouponID.length == 0) {

        if (WholeCouponID == "") {
          obj.ReceiveCouponID = 0
        } else {
          obj.ReceiveCouponID = WholeCouponID
        }

      } else {
        if (WholeCouponID == "") {
          obj.ReceiveCouponID = JSCouponID.join(',')
        } else {
          obj.ReceiveCouponID = WholeCouponID + "," + JSCouponID.join(',')
        }
      }
    } else {
      if (WholeCouponID == "") {
        if (JSCouponID == "") {
          obj.ReceiveCouponID = 0
        } else {
          obj.ReceiveCouponID = JSCouponID
        }
      } else {
        if (JSCouponID == "") {
          obj.ReceiveCouponID = WholeCouponID
        } else {
          obj.ReceiveCouponID = WholeCouponID + "," + JSCouponID
        }
      }
    }


    // obj.InvoiceID: -1,
    obj.IMoney = this.data.allmoney
    obj.Remark = this.data.bz
    // obj.PersonAddress: 122,
    // obj.Remark: ,

    for (var x in info.data) {
      var obj1 = {}
      obj1.PGID = info.data[x].ID
      obj1.SKUID = info.data[x].SKUID
      obj1.OrderNumber = info.data[x].OrderNumber
      obj1.CartID = info.data[x].CartIDStr
      Orders.push(obj1)
    }

    obj.Orders = Orders
    query.push(obj)
    console.log(query, 'query')
    ajax('/api/OrderInsertShop/OrderInsert?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      query: query

    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "post",
    }, res => {

      if (res.Message == "上传成功!") {
        console.log(res)


        this.setData({
          ordermsg: res.Model
        })

        wx.redirectTo({
          url: '/pages/pay/pay?orderid=' + this.data.ordermsg.OrderID + '&ordercode=' + this.data.ordermsg.iCode + '&OrderType=' + 5,
        })

      } else {
        wx.showToast({
          title: '提交订单失败',
          icon: 'none',
          duration: 2000
        })
      }

    })
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      canclick: true
    })

    if (wx.getStorageSync("siteid")) {
      var siteid = wx.getStorageSync("siteid")
      console.log(siteid)

      this.setData({
        siteid: siteid
      })

    }

    if (this.data.active == 2) {
      this.getlistalladdress(1, this.data.siteid)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})